//
//  CommonSwift.swift
//  WenZhouQuan
//
//  Created by Meeno04 on 15/12/26.
//  Copyright © 2015年 meeno. All rights reserved.
//

import Foundation
import UIKit
import AVFoundation

public extension String {
    
    func boundRect(size:CGSize, attribute:[NSAttributedString.Key: AnyObject], option:NSStringDrawingOptions = .usesLineFragmentOrigin) -> CGRect{
        
        let string = NSString.init(string: self)
        let stringBound = string.boundingRect(with: size, options: option, attributes: attribute, context: nil)
        return stringBound
    }
    
    func toURL() -> NSURL?{
       return NSURL(string: self)
    }
}

public extension Bundle{
    static func getBundle(name:String) -> Bundle? {
        if let url = Bundle.main.url(forResource: name, withExtension: "bundle"){
            return Bundle(url: url)
        }
        return nil
    }
}


public extension String {
    
    func hexIntegerValue() -> Int{
        let tempStr = self.uppercased()
        var hexInt:Int = 0
        for char in tempStr{
            switch char {
            case "A":
                hexInt += 10
            case "B":
                hexInt += 11
            case "C":
                hexInt += 12
            case "D":
                hexInt += 13
            case "E":
                hexInt += 14
            case "F":
                hexInt += 15
            case "0"..."9":
                hexInt += Int(String(char))!
            default:
                return 0
            }
            hexInt <<= 4
        }
        hexInt >>= 4
        return hexInt
    }
    
    static func hexString( hexInteger:Int) -> String{
        if hexInteger == 0 {
            return "0";
        }
        
        var str = String()
        let hexMap = [
            0:"0",
            1:"1",
            2:"2",
            3:"3",
            4:"4",
            5:"5",
            6:"6",
            7:"7",
            8:"8",
            9:"9",
            10:"A",
            11:"B",
            12:"C",
            13:"D",
            14:"E",
            15:"F",
            ];
        var tempHexInteger = hexInteger
        while  tempHexInteger != 0{
            let value = tempHexInteger & 0xf
            let chars = hexMap[value]
            str.insert(chars![(chars?.startIndex)!], at: chars!.startIndex)
            tempHexInteger >>= 4
        }
        
        return str
    }
}

public extension NSString
{
    
    func hexIntegerValue() -> Int{
        let s = String(self)
        return s.hexIntegerValue()
    }
    
}

public extension UIColor{
    
     convenience init(HEXValue hexValue:Int, alpha:Float = 1.0){
        
        let red = Float(((hexValue & 0xff0000) >> 16)) / Float(255.0)
        let green = Float(((hexValue & 0x00ff00) >> 8)) / Float(255.0)
        let blue = Float(hexValue & 0xff) / Float(255.0)
        
        self.init(red: CGFloat(red), green:CGFloat(green), blue:CGFloat(blue), alpha:CGFloat(alpha))
    }
    
    static func createImage(color:UIColor, size:CGSize) -> UIImage{
        
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image!
    }
}

public extension Date{
    static func dateWith(formatString:String, dateString:String) -> Date?{
        let format = DateFormatter()
        format.dateFormat = formatString
        return format.date(from: dateString)
    }
    
    static func dateStringToDateString(dateString:String, originalformatString: String, outputFormatString: String) -> String?{
        let date = dateWith(formatString: originalformatString, dateString: dateString)
        return date?.dateString(formatString: outputFormatString)
    }
    
    func isThisYearApp() ->Bool{
      return self.dateString(formatString: "yyyy") == Date().dateString(formatString: "yyyy")
    }
    
    func dateString(formatString: String) -> String{
        let format = DateFormatter()
        format.dateFormat = formatString
        return format.string(from: self)
    }
    
    func calcAge() -> String{
        let birthdayComponents = Calendar.current.dateComponents([.day, .month, .year], from: self)
        let currentComponents = Calendar.current.dateComponents([.day, .month, .year], from: Date())
        
        var myAge = currentComponents.year! - birthdayComponents.year!
        
        if(currentComponents.month! > birthdayComponents.month!){
            myAge += 1
        }else if(currentComponents.month! == birthdayComponents.month! && currentComponents.day! >= birthdayComponents.day!){
            myAge += 1
        }
        
        return String(myAge)
    }
}

public extension UIImage{
    static func getImage(videoUrl: URL) -> UIImage?{
        
            let asset = AVURLAsset(url: videoUrl)
            let imageGenerator = AVAssetImageGenerator(asset: asset)
            imageGenerator.appliesPreferredTrackTransform = true
            
            do{
                //            let actualTime:UnsafeMutablePointer<CMTime> = UnsafeMutablePointer<CMTime>.init()
                let image = try imageGenerator.copyCGImage(at: CMTime(seconds: 0, preferredTimescale: 60), actualTime: nil)
                let image_1 = UIImage(cgImage: image)
                return image_1
            }catch{
                print(error)
                return nil
            }
            
    }
    
    func getDateRandomName() -> String {
        
        func getDateString() -> String{
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd-HH-mm-ss"
            return formatter.string(from: Date())
            
        }
        
        func getRandomString(length:Int) -> String{
            let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
            var randomString = String()
            for _ in 0...length{
                let index = arc4random_uniform(UInt32.init( letters.count))
                let char = letters[letters.index(letters.startIndex, offsetBy: Int(index))]
                randomString.append(char)
            }
            return randomString
        }
        let result = String(format: "\(getDateString())_\(getRandomString(length: 8)).png")
        
        print(result)
        return result;
    }
    
    func fixOrientation() -> UIImage?{
        if self.imageOrientation == .up{
           return self
        }
        
        var transform = CGAffineTransform.identity
        
        switch self.imageOrientation {
        case .down, .downMirrored:
            transform = transform.translatedBy(x: self.size.width, y: self.size.height)
            transform = transform.rotated(by: CGFloat(Double.pi))
        case .left, .leftMirrored:
            transform = transform.translatedBy(x: self.size.width, y: 0)
            transform = transform.rotated(by: CGFloat(Double.pi))
        case .right, .rightMirrored:
            transform = transform.translatedBy(x: 0, y: self.size.height)
            transform = transform.rotated(by: CGFloat(-Double.pi))
        default:
            break
        }
        
        switch self.imageOrientation {
        case .upMirrored, .downMirrored:
            transform = transform.translatedBy(x: self.size.width, y: 0)
            transform = transform.scaledBy(x: -1, y: 1)
            
        default:
            break
        }
        
        switch self.imageOrientation {
        case .leftMirrored, .rightMirrored:
            transform = transform.translatedBy(x: self.size.height, y: 0)
            transform = transform.scaledBy(x: -1, y: 1)
            
        default:
            break
        }
       let ctx = CGContext.init(data: nil,
                       width: Int(self.size.width),
                       height: Int(self.size.height),
                       bitsPerComponent: self.cgImage!.bitsPerComponent ,
                       bytesPerRow: self.cgImage!.bytesPerRow,
                       space: self.cgImage!.colorSpace!,
                       bitmapInfo: self.cgImage!.bitmapInfo.rawValue)
        
        switch self.imageOrientation {
        case .left, .leftMirrored, .right, .rightMirrored:
            ctx?.draw(self.cgImage!, in: CGRect.init(x: 0, y: 0, width: self.size.height, height: self.size.width))
        default:
            ctx?.draw(self.cgImage!, in: CGRect.init(x: 0, y: 0, width: self.size.width, height: self.size.height))
            break
        }
        
        if let cimg = ctx?.makeImage() {
            return UIImage(cgImage: cimg)
        }
        
        return nil
        
    }

}

public extension UIViewController{
    func preViewController(preIndex:Int) -> UIViewController? {
        if let aNav = self.navigationController {
            if aNav.viewControllers.count > preIndex {
                return aNav.viewControllers[aNav.viewControllers.count - 1 - preIndex]
            }else{
                print("preIndex is to big")
               return nil
            }
        }else{
            print("viewController has no navigationController!")
           return nil
        }
    }
}

public extension UIApplication{
    static func normalLevelWindow() -> UIWindow?{
        var normalWindow:UIWindow?
        _ = self.shared.windows.map { (x:UIWindow) -> Void in
            if x.windowLevel == UIWindow.Level.normal{
                normalWindow = x
            }
        }
        
        return normalWindow
    }
}
extension UserDefaults {
    subscript(key: String) -> Any? {
        set {
            self.set(newValue, forKey: key)
        }
        
        get {
            return self.value(forKey: key)
        }
    }
}

public extension Data {
    func getUInt8Arr() -> [UInt8] {
        return self.withUnsafeBytes{
                [UInt8](UnsafeBufferPointer(start: $0, count: self.count))
            }
    }
}

//
//  UIImage+Extension.swift
//  逗牛
//
//  Created by mac on 16/3/7.
//  Copyright © 2016年 mac. All rights reserved.
//
public extension UIImage {
    
    //    ///对指定图片进行拉伸
    func my_resizableImage() -> UIImage {
        
        let imageWidth = self.size.width * 0.5
        let imageHeight = self.size.height * 0.5
        let normal = resizableImage(withCapInsets: UIEdgeInsets(top: imageHeight, left: imageWidth, bottom: imageHeight, right: imageWidth))
        
        return normal
    }
    
    /**
     *  压缩上传图片到指定字节
     *
     *  image     压缩的图片
     *  maxLength 压缩后最大字节大小
     *
     *  return 压缩后图片的二进制
     */
    func compressImage(maxLength: Int) -> Data? {
        
        let newSize = self.scaleImage(imageLength: 300)
        guard let newImage = self.resizeImage(newSize: newSize) else {
            return nil
        }
        
        var compress:CGFloat = 0.9
        
        guard var data = newImage.jpegData(compressionQuality: compress) else {
            return nil
        }
        
        
        while data.count > maxLength && compress > 0.01 {
            compress -= 0.02
            guard let x =  newImage.jpegData(compressionQuality: compress) else {
                return nil
            }
            
            data = x
        }
        
        return data
    }
    
    /**
     *  通过指定图片最长边，获得等比例的图片size
     *
     *  image       原始图片
     *  imageLength 图片允许的最长宽度（高度）
     *
     *  return 获得等比例的size
     */
    func  scaleImage(imageLength: CGFloat) -> CGSize {
        
        var newWidth:CGFloat = 0.0
        var newHeight:CGFloat = 0.0
        let width = self.size.width
        let height = self.size.height
        
        if (width > imageLength || height > imageLength){
            
            if (width > height) {
                
                newWidth = imageLength;
                newHeight = newWidth * height / width;
                
            }else if(height > width){
                
                newHeight = imageLength;
                newWidth = newHeight * width / height;
                
            }else{
                
                newWidth = imageLength;
                newHeight = imageLength;
            }
            
        }
        return CGSize(width: newWidth, height: newHeight)
    }
    
    /**
     *  获得指定size的图片
     *
     *  image   原始图片
     *  newSize 指定的size
     *
     *  return 调整后的图片
     */
    func resizeImage(newSize: CGSize) -> UIImage? {
        UIGraphicsBeginImageContext(newSize)
        self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage
    }
    
}
